const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const DepartmentPermission = sequelize.define('DepartmentPermission', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '权限ID'
  },
  department_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '部门ID'
  },
  template_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '权限模板ID'
  },
  permissions: {
    type: DataTypes.JSON,
    allowNull: false,
    comment: '部门权限配置（JSON格式）'
  }
}, {
  tableName: 'department_permissions',
  timestamps: true,
  indexes: [
    {
      unique: true,
      fields: ['department_id', 'template_id']
    }
  ]
})

// 延迟设置关联关系，避免循环依赖
setTimeout(() => {
  const Department = require('./department')
  const PermissionTemplate = require('./PermissionTemplate')

  DepartmentPermission.belongsTo(Department, {
    foreignKey: 'department_id',
    as: 'department'
  })

  DepartmentPermission.belongsTo(PermissionTemplate, {
    foreignKey: 'template_id',
    as: 'template'
  })
}, 0)

module.exports = DepartmentPermission 